package com.engine.jucailinkq.attendance.workflow.proxy.tactics;

import com.alibaba.fastjson.JSONObject;
import com.engine.jucailinkq.attendance.workflow.enums.WorkFlowTypeEnum;
import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.engine.jucailinkq.common.util.Utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 请假流程删除、退回等进行假期余额重置
 */
@Slf4j
public class AskForLeaveWorkflowDataReset implements WorkFlowHandleTacis{
    @Override
    public boolean support(String personClassfiy) {
        if (personClassfiy.equals(WorkFlowTypeEnum.ASKFORLEAVE.getKey())){
            return true;
        }
        return false;
    }

    @Override
    public void reset(Map<String, Object> requestMap) {
        log.info("AskForLeaveWorkflow requestMap: [{}]",requestMap);
        String tableName = requestMap.get("lcbd").toString();
        String requestId = requestMap.get("requestId").toString();
        String operate = requestMap.get("operate").toString();

        Map<String,Object> mainMap = null;
        List<Map<String, Object>> detailTableData = null;
        List<Map<String, Object>> detailTable2 = null;


        if (operate.equals("dodelete")){
            //删除流程
            String sql = "select deletetabledata from workflow_requestdeletelog where request_id=? and (isvalid is null or  isvalid <> '1')";
            List<Map<String, Object>> deleteDataList = DbTools.getSqlToList(sql,requestId);
            if (deleteDataList.size() > 0){
                String deletetabledata = deleteDataList.get(0).get("deletetabledata").toString();
                Map<String, List<Map<String, Object>>> map = (Map<String, List<Map<String, Object>>>) JSONObject.parse(deletetabledata);
                mainMap = keyToLowerMap(map.get(tableName).get(0));
                detailTableData = keyToLowerList(map.get(tableName+"_dt1"));
                detailTable2 = keyToLowerList(map.get(tableName+"_dt2"));
            }
        }else {
            String sql = "select * from "+tableName+" where requestid=?";
            mainMap = DbTools.getSqlToList(sql,requestId).get(0);

            // 流程表单明细表1数据
            sql = "select * from "+tableName+"_dt1 where mainid=?";
            detailTableData = DbTools.getSqlToList(sql,mainMap.get("id"));

            //流程表单明细表2数据
            sql = "select * from "+tableName+"_dt2 where mainid=?";
            detailTable2 = DbTools.getSqlToList(sql,mainMap.get("id"));
        }
        log.info("detailTableData : [{}]",detailTableData);
        log.info("BatchAskForLeaveWorkFlowBackAction-detailTable2Data : [{}]",detailTable2);
        if (mainMap == null || detailTable2 == null || detailTableData == null){
            return;
        }

        String sql = "select id, jlzt from uf_jcl_kq_qjjl where djid = " + requestId;
        Map<String, Object> qjllData = DbTools.getSqlToMap(sql);
        String jlzt = Util.null2String(qjllData.get("jlzt"));


        sql = "select id,jqid,sxrq,ktsc,yxsc,wxsc,yqsxrq,ztsc from uf_jcl_kq_jqye order by sxrq";

        List<Map<String,Object>> holidayBalanceList = DbTools.getSqlToList(sql);

        Map<String,Object> holidayBalanceMap = holidayBalanceList.stream().collect(Collectors.toMap(e->e.get("id").toString(), e->e));

        try {
            if (detailTable2.size() > 0) {
                Map<String,Object> balanceMap = Maps.newHashMap();
                for (Map<String, Object> data : detailTable2){
                    String jqye = Util.null2String(data.get("jqye"));
                    double sysc = Double.valueOf(data.get("sysc").toString());
                    double havedSysc= balanceMap.get(jqye) ==null?0:Double.valueOf(balanceMap.get(jqye).toString());
                    sysc = Utils.add(sysc,havedSysc);
                    balanceMap.put(jqye,sysc);
                }
                log.info("balanceMap : [{}]",balanceMap);
                for (Map.Entry<String,Object> entry:balanceMap.entrySet()){
                    String id = entry.getKey();
                    double ztsc = Double.valueOf(entry.getValue().toString());
                    Map<String,Object> map =  (Map<String,Object>)holidayBalanceMap.get(id);
                    boolean updateSign = true;
                    log.info("jlzt : [{}]",jlzt);
                    if ("1".equals(jlzt)) {
                        double havedyxsc = Util.null2String(map.get("yxsc")).equals("") ? 0 : Double.valueOf(map.get("yxsc").toString());
                        double havedwxsc = Util.null2String(map.get("wxsc")).equals("") ? 0 : Double.valueOf(map.get("wxsc").toString());
                        double updatedyxsc = Utils.subtract(havedyxsc,ztsc);
                        double updatedwxsc = Utils.add(havedwxsc,ztsc);

                        log.info("updatedyxsc : [{}],id:[{}]",updatedyxsc,id);
                        String updateSql = "update uf_jcl_kq_jqye set wxsc=?,yxsc=? where id=?";
                        updateSign = DbTools.update(updateSql,updatedwxsc, updatedyxsc,id);
                    } else if("0".equals(jlzt)){
                        double havedztsc = Util.null2String(map.get("ztsc")).equals("") ? 0 : Double.valueOf(map.get("ztsc").toString());
                        double havedwxsc = Util.null2String(map.get("wxsc")).equals("") ? 0 : Double.valueOf(map.get("wxsc").toString());

                        double updatedztsc = Utils.subtract(havedztsc,ztsc);
                        double updatedwxsc = Utils.add(havedwxsc,ztsc);

                        log.info("updatedwxsc : [{}],updatedztsc:[{}],id:[{}]",updatedwxsc,updatedztsc,id);
                        String updateSql = "update uf_jcl_kq_jqye set wxsc=?,ztsc=? where id=?";
                        updateSign = DbTools.update(updateSql,updatedwxsc,updatedztsc,id);
                    }

                    log.info("updateSign : [{}]",updateSign);
                }
            }

            //删除请假记录
            if ("1".equals(jlzt) || "0".equals(jlzt)) {
                String qjjlMainId = Util.null2String(qjllData.get("id"));
                if (!"".equals(qjjlMainId)) {
                    String delteSql = "delete from uf_jcl_kq_qjjl_dt1 where mainid = " + qjjlMainId;
                    boolean delSignDt1 = DbTools.update(delteSql);
                    delteSql = "delete from uf_jcl_kq_qjjl_dt2 where mainid = " + qjjlMainId;
                    boolean delSignDt2 = DbTools.update(delteSql);
                    delteSql = "delete from uf_jcl_kq_qjjl where id = " + qjjlMainId;
                    boolean delSignMain = DbTools.update(delteSql);
                    if (!delSignDt1 || !delSignDt2 || !delSignMain) {
                        String message = "删除假期记录失败";
                        log.error(message);
                    }
                }
            }
            //将明细表1数据清空
            String delSql = "delete from " + tableName + "_dt1 where mainid=?";
            if (!DbTools.update(delSql, mainMap.get("id"))) {
                //将明细表1数据清空
                String message = "删除流程明细表1数据失败";
                log.error(message);
            }

            //将明细表2数据清空
            delSql = "delete from " + tableName + "_dt2 where mainid=?";
            if (!DbTools.update(delSql, mainMap.get("id"))) {
                //将明细表2数据清空
                String message = "删除流程明细表2数据失败";
                log.error(message);
            }

        }catch (Exception e){
            log.error("BatchAskForLeaveWorkFlowBackAction error : [{}]",e);
        }
    }

    public Map<String,Object> keyToLowerMap(Map<String,Object> map){
        Map<String,Object> resultMap = Maps.newHashMap();
        map.entrySet().forEach(e->{
            resultMap.put(e.getKey().toLowerCase(),e.getValue());
        });
        return resultMap;
    }
    public List<Map<String,Object>> keyToLowerList(List<Map<String,Object>> list){
        List<Map<String,Object>> resultList = Lists.newArrayList();
        for (Map<String,Object> map:list){
            resultList.add(keyToLowerMap(map));
        }
        return resultList;
    }
}
